#include "../include/muduo/net/TcpServer.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/TcpConnection.h"

#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateServer
{
public:
    TranslateServer(uint16_t port):_server
        (&_baseloop,muduo::net::InetAddress("0.0.0.0",port),
        "TranslateServer",muduo::net::TcpServer::kReusePort)
    {
        // 客户端连接建立 / 关闭时触发,有链接来了怎么做
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection,this,std::placeholders::_1));
        // 客户端发送数据时触发,有事件来了怎么做
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage,this,
            std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }

    void start()
    {
        _server.start(); // 启动服务器。开始监听
        _baseloop.loop(); // 进入事件循环，阻塞等待事件
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout<<"新连接建立成功"<<std::endl;
        }
        else
        {
            std::cout<<"新连接关闭"<<std::endl;
        }
    }

    std::string translate(const std::string& str)
    {
        static std::unordered_map<std::string,std::string> dict_map = {
            {"hello","你好"},
            {"HELLO","你好"},
            {"你好","hello"},
        };
        auto iter = dict_map.find(str);
        if(iter == dict_map.end())
        {
            return "没听懂";
        }
        else 
        {
            return iter->second;
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buf,muduo::Timestamp timee)
    {
        // 从buffer中获取对应的数据
        std::string str = buf->retrieveAllAsString();
        // 进行翻译
        std::string ret = translate(str);
        // 响应给客户端
        conn->send(ret);
    }
private:
    muduo::net::EventLoop _baseloop; // 负责处理 IO 事件、定时器事件等
    muduo::net::TcpServer _server; // 用于管理客户端连接和数据收发
};

int main()
{
    TranslateServer conn(8080);
    conn.start();
    return 0;
}